package com.lin.service;

import com.lin.spring.BeanPostProcessor;
import com.lin.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName MyPostProcessor
 * @Description
 * @Author lin
 * @Date 2022/4/5 上午2:10
 * @Version V1.0
 */
@Component
public class MyPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if("userService".equals(beanName)){
            System.out.println("userService在初始化之前做一些事");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        // 如果事aop的类，可以返回代理对象
        if("userService".equals(beanName)){
            Object proxyInstance = Proxy.newProxyInstance(MyPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    return method.invoke(bean, args);
                }
            });
            return proxyInstance;
            // System.out.println("userService在初始化之后做一些事");
        }
        return bean;
    }
}
